var express = require('express');
var router = express.Router();
const fs = require("fs");
const path = require("path");
const banner = require("../sql/banner");
const sql = require("../sql/sql");
const uuid = require("uuid");

router.get('/', function(req, res, next) {
  // 需要权限验证的路由，先获取用户权限级别，再做页面渲染
  if(req.session.power === 0){
    res.render("nopower")
  }else{
    sql.get(banner).then(data=>{
      res.render('banner', {
        index: 2,
        data,
        power: req.session.power
      });
    })
  }
});

router.post('/add', function(req, res, next) {
  const data = req.body;
  const file = req.files[0];

  const oldName = path.join(__dirname, "..", file.path);
  const newName = oldName + "-" + file.originalname;

  const p = "http://localhost:3000" + newName.split("public")[1];

  fs.rename(oldName, newName, ()=>{
    sql.add(banner,{
      bannerId: "bannerId-" + uuid.v1(),
      alt: data.alt,
      title: data.title,
      src: p,
      time: Date.now()
    }).then(()=>{
      res.redirect("/banner");
    })
  });
});

module.exports = router;
